﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using VO.Business.Controllers;
using VO.Business.Utils;
using VO.Entities;

namespace VO.Web
{
    public partial class UserProfile : System.Web.UI.Page
    {

        public bool ClearPicture
        {
            get {
                if (Session["ClearPicture"] != null)
                    return (bool)Session["ClearPicture"];
                return false;   
            }
            set { Session["ClearPicture"] = value; }
        }

        public string UserLogoFile
        {
            get
            {
                return Session["UserLogoFile"] as string;
            }
            set
            {
                Session["UserLogoFile"] = value;
            }
        }

        public bool IsCropping
        {
            get
            {
                return (bool)Session["IsCropping"];
            }
            set
            {
                Session["IsCropping"] = value;
            }
        }

        private User _user;
        public User GetCurrentUser()
        {
            if (_user == null)
            {
                MembershipUser mUser = Membership.GetUser();
                if (mUser != null)
                {
                    Guid idMembership = new Guid(mUser.ProviderUserKey.ToString());
                    _user = UsersController.GetUserByIdMembership(idMembership);
                }
            }
            return _user;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            User user = GetCurrentUser();
            if (!IsPostBack)
            {
                IsCropping = false;
                UserLogoFile = null;
                ClearPicture = false;
                Master.MessageText = string.Empty;
                txtDescription.Text = user.UserDescription;
                txtPublicName.Text = user.PublicName;
                txtLoginUserName.Text = Membership.GetUser(user.IdMembership).UserName;
            }

            if(!IsCropping)
                imgUserLogo.ImageUrl = string.Format("~/UserLogo.ashx?uid={0}&t={1}{2}", user.Id, DateTime.Now.Ticks.ToString(), ClearPicture ? "&clear=1" : "");

            UpdateCropper();
        }

        private void UpdateCropper()
        {
            pnlCropUploadedFullScreen.CssClass = IsCropping ? "pnlCropUploadedFullScreen" : "pnlCropUploadedFullScreenHidden";
            imageToCrop.ImageUrl = IsCropping ? "~/tempImages/" + UserLogoFile + "?rnd=" + Guid.NewGuid().ToString() : string.Empty;
        }

        protected void btnSaveUserProfile_Click(object sender, EventArgs e)
        {
            //TODO - save user profile
            User user = GetCurrentUser();
            user.UserDescription = txtDescription.Text;
            user.PublicName = txtPublicName.Text;
            if (ClearPicture)
            {
                user.UserLogo = null;
            }
            else
            {
                if (UserLogoFile != null)
                {
                    byte[] fileContent = File.ReadAllBytes(Server.MapPath("~/tempImages/" + UserLogoFile));
                    user.UserLogo = fileContent;
                }
            }
            UsersController.SaveUser(user, false);
            Master.MessageText = "Save succesful!";
            Master.MasterUserName = user.PublicName;
        }

        protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            byte[] buffer = new byte[AsyncFileUpload1.FileContent.Length];
            AsyncFileUpload1.FileContent.Read(buffer, 0, (int)AsyncFileUpload1.FileContent.Length);
            //
            User user = GetCurrentUser();
            //
            ClearPicture = false;
            //fill croping tool
            UserLogoFile = Guid.NewGuid().ToString() + AsyncFileUpload1.FileName.Substring(AsyncFileUpload1.FileName.LastIndexOf("."));
            using (FileStream fs = File.Create(Server.MapPath("~/tempImages") + "/" + UserLogoFile))
            {    
                fs.Write(buffer, 0, buffer.Length);
            }
            IsCropping = true;            
        }

        protected void btnClearLogo_Click(object sender, EventArgs e)
        {
            UserLogoFile = null;
            ClearPicture = true;
            User user = GetCurrentUser();
            imgUserLogo.ImageUrl = string.Format("~/UserLogo.ashx?uid={0}&t={1}{2}", user.Id, DateTime.Now.Ticks.ToString(), ClearPicture ? "&clear=1" : "");
        }

        protected void btnCrop_Click(object sender, EventArgs e)
        {
            cropImage.Crop(Server.MapPath("~/tempImages/" + UserLogoFile));
            cropImage.X = 0;
            cropImage.Y = 0;
            cropImage.X2 = cropImage.CanvasWidth;
            cropImage.Y2 = cropImage.CanvasHeight;
        }

        protected void btnCropSave_Click(object sender, EventArgs e)
        {
            IsCropping = false;
            string file = Server.MapPath("~/tempImages/" + UserLogoFile);
            ImageResizer.ResizeImage(file, ImageFormat.Jpeg, 100, 100);
            //update logo image
            User user = GetCurrentUser();
            imgUserLogo.ImageUrl = string.Format("~/UserLogo.ashx?uid={0}&t={1}{2}", user.Id, DateTime.Now.Ticks.ToString(), ClearPicture ? "&clear=1" : "");
            UpdateCropper();            
        }

        protected void btnCropCancel_Click(object sender, EventArgs e)
        {
            IsCropping = false;
            UserLogoFile = null;
            //
            UpdateCropper();
        }

    }
}